var deviceInfo = function() {
    document.getElementById("platform").innerHTML = device.platform;
    document.getElementById("version").innerHTML = device.version;
    document.getElementById("uuid").innerHTML = device.uuid;
    document.getElementById("name").innerHTML = device.name;
    document.getElementById("width").innerHTML = screen.width;
    document.getElementById("height").innerHTML = screen.height;
    document.getElementById("colorDepth").innerHTML = screen.colorDepth;
};

var getLocation = function() {
    var suc = function(p) {
        alert(p.coords.latitude + " " + p.coords.longitude);
    };
    var locFail = function() {
        navigator.notification.alert(
                'Unable to locate.',  // message
                alertDismissed,         // callback
                'Location info',            // title
                'Done'                  // buttonName
            );	    	
    };
    navigator.geolocation.getCurrentPosition(suc, locFail);
};

var beep = function() {
    navigator.notification.beep(2);
};

var vibrate = function() {
    navigator.notification.vibrate(0);
};

function roundNumber(num) {
    var dec = 3;
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

var accelerationWatch = null;

function updateAcceleration(a) {
    document.getElementById('x').innerHTML = roundNumber(a.x);
    document.getElementById('y').innerHTML = roundNumber(a.y);
    document.getElementById('z').innerHTML = roundNumber(a.z);
}

var toggleAccel = function() {
    if (accelerationWatch !== null) {
        navigator.accelerometer.clearWatch(accelerationWatch);
        updateAcceleration({
            x : "",
            y : "",
            z : ""
        });
        accelerationWatch = null;
    } else {
        var options = {};
        options.frequency = 2000;
        accelerationWatch = navigator.accelerometer.watchAcceleration(
                updateAcceleration, function(ex) {
                    alert("accel fail (" + ex.name + ": " + ex.message + ")");
                    navigator.accelerometer.clearWatch(accelerationWatch);
                }, options);
    }
};

var preventBehavior = function(e) {
    e.preventDefault();
};

function dump_pic(data) {
    var viewport = document.getElementById('viewport');
    console.log(data);
    viewport.style.display = "";
    viewport.style.position = "absolute";
    viewport.style.top = "10px";
    viewport.style.left = "10px";
    document.getElementById("test_img").src = "data:image/jpeg;base64," + data;
}

function fail(msg) {
    alert(msg);
}

function show_pic() {
    navigator.camera.getPicture(dump_pic, fail, {
        quality : 50
    });
}

function close() {
    var viewport = document.getElementById('viewport');
    viewport.style.position = "relative";
    viewport.style.display = "none";
}

function contacts_success(contacts) {
	$("#contacts #contactsList").html(" ");
	var output='';
	contacts.forEach(function(item) {
		output+='<li class="ui-li ui-li-static ui-body-c ui-li-has-thumb"><img src="" class="ui-li-thumb"><h3 class="ui-li-heading">'+item.name.formatted+'</h3></li>';
	});
	$("#contacts #contactsList").html(output);
}

function get_contacts() {
    var obj = new ContactFindOptions();
    obj.filter = "";
    obj.multiple = true;
    obj.limit = 5;
    navigator.contacts.find(
            [ "displayName", "name", "photos" ], contacts_success,
            fail, obj);
}

function check_network() {
	var networkState=navigator.network.connection.type;

    navigator.notification.alert(
            networkState,  // message
            alertDismissed,         // callback
            'Connection info',            // title
            'Done'                  // buttonName
        );	
}

function alertDismissed() {
    // do something
}

function showAlert() {
    navigator.notification.alert(
        'You are the winner!',  // message
        alertDismissed,         // callback
        'Game Over',            // title
        'Done'                  // buttonName
    );
}

function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}

function gotFileWriter(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.write("some sample text");
    // contents of file now 'some sample text'
    writer.truncate(11);
    // contents of file now 'some sample'
    writer.seek(4);
    // contents of file still 'some sample' but file pointer is after the 'e' in 'some'
    writer.write(" different text");
    // contents of file now 'some different text'
}

function fail(error) {
	alert("fail");
}


function writeToFile(path,text) {
	
}

function init() { //app done loading
	document.addEventListener("deviceready", deviceInfo, true);
    
    $("#alert").click(function() {
        showAlert();
      }); 
    
    if (window.PalmSystem) {
        window.PalmSystem.stageReady();
    }    
    
    $("#loadContacts").click(function() {
    	get_contacts();		
    });
    
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

    $("#fileTest").click(function() {
    	//writeToFile('/sdcard/test.txt','testovaci text');
    	//readFromFile('/sdcard/test.txt');
    });
}

$('div:jqmData(role="page")').live('pagebeforeshow',function(){ //page done loading

});

$('div:jqmData(role="page")').live('pageshow',function(){ //page done loading
	
});
